/**
* Created by bill on 18/5/08.
*/

import axios from 'axios'
import qs from 'qs';
import _ from 'lodash';

// create an axios instance
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 5000, // request timeout
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    // params: {
    //     token: store.state.token
    // },
    // `transformRequest` 允许在向服务器发送前，修改请求数据
    // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
    transformRequest: [
        function (data) {
            return qs.stringify(data)
        }
    ],
    // `transformResponse` 在传递给 then/catch 前，允许修改响应数据
    transformResponse: [function (data) {
        // 这里提前处理返回的数据
        let da = JSON.parse(data)
        if(da.code != 200){
            Promise.reject(da.msg)
        }else {
            return data;
        }
    }],
    paramsSerializer(data) {
        return qs.stringify(data);
    }

})

// request interceptor
service.interceptors.request.use(config => {
    // Do something before request is sent
    //设置自定义请求头
    // config.headers['Authorization'] = 'Bearer '+getToken()||''

    return config
}, error => {
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
    response => {
        response.data = _.isString(response.data) ? JSON.parse(response.data) : response.data;
        return response.data;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    })

export default service

